package com.fragrance.cfg;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fragrance.controller.DeviceController;
import com.fragrance.controller.UserInnerController;
import com.fragrance.controller.UserOpenController;
import com.fragrance.controller.WeChatDeviceOprController;
import com.fragrance.controller.WeChatInnerUserController;
import com.fragrance.controller.WeChatMsgController;
import com.fragrance.controller.WeChatOpenUserController;
import com.fragrance.interceptor.LoginInterceptor;
import com.fragrance.listener.IotMnsTaskListener;
import com.fragrance.model.CfgModel;
import com.fragrance.model.DeviceMainModel;
import com.fragrance.model.RightModel;
import com.fragrance.model.RoleModel;
import com.fragrance.model.RoleRrightCfgModel;
import com.fragrance.model.UserAccountModel;
import com.fragrance.model.UserDeviceBindModel;
import com.fragrance.model.UserDeviceModel;
import com.fragrance.model.UserRoleCfgModel;
import com.fragrance.model.WxUserModel;
import com.fragrance.quartz.QuartzPlugin;
import com.jfinal.config.Constants;
import com.jfinal.config.Handlers;
import com.jfinal.config.Interceptors;
import com.jfinal.config.JFinalConfig;
import com.jfinal.config.Plugins;
import com.jfinal.config.Routes;
import com.jfinal.kit.Prop;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.druid.DruidPlugin;
import com.jfinal.plugin.redis.RedisPlugin;
import com.jfinal.template.Engine;

public class FragranceJFinalCfg extends JFinalConfig {

	private Logger logger = LoggerFactory.getLogger(FragranceJFinalCfg.class);
	
	private Prop jdbcProp = null;
 
	private Prop redisProp = null;
	
	public static Prop weChatProp = null; 
	
	public static Prop iotcfgProp = null;
	

	/**
	 * 此方法用来配置JFinal常量值，如开发模式常量devMode的配置，如下代码配置了JFinal运行在开发模式： public void
	 * configConstant(Constants me) { me.setDevMode(true); }
	 * 在开发模式下，JFinal会对每次请求输出报告，如输出本次请求的URL、Controller、Method以及请求所携带的参数。
	 */
	@Override
	public void configConstant(Constants me) {
		me.setDevMode(true);
		me.setBaseUploadPath("upload/");  
		jdbcProp = PropKit.use("jdbc.properties");
		redisProp = PropKit.use("redis.properties");
		weChatProp = PropKit.use("wechat.properties");
		iotcfgProp = PropKit.use("iotcfg.properties");
	}

	@Override
	public void configEngine(Engine me) {
		// TODO Auto-generated method stub

	}

	@Override
	public void configHandler(Handlers me) {
		// TODO Auto-generated method stub

	}

	@Override
	public void configInterceptor(Interceptors me) {
		// TODO Auto-generated method stub

	}

	@Override
	public void configPlugin(Plugins me) {
		DruidPlugin dp = new DruidPlugin(jdbcProp.get("jdbcUrl"), //
				jdbcProp.get("userName"), //
				jdbcProp.get("password"), //
				jdbcProp.get("driver"));
		me.add(dp);
		// 数据库映射
		ActiveRecordPlugin arp = new ActiveRecordPlugin(dp);
		arp.setShowSql(true);
		//后台权限管理
		arp.addMapping("oms_cfg_right", "id", RightModel.class);
		arp.addMapping("oms_cfg_role", "id", RoleModel.class);
		arp.addMapping("oms_cfg_role_right", "id", RoleRrightCfgModel.class);
		arp.addMapping("oms_cfg_user_role", "id", UserRoleCfgModel.class);
		arp.addMapping("oms_account_main", "id", UserAccountModel.class);
		//配置表
		arp.addMapping("t_cfg", "id", CfgModel.class);
		//微信用户表
		arp.addMapping("t_wx_user", "id", WxUserModel.class);
		//设备信息表
		arp.addMapping("t_device_main", "id", DeviceMainModel.class);
		//设备使用情况表
		arp.addMapping("t_user_device", "id", UserDeviceModel.class);
		//设备绑定情况表
		arp.addMapping("t_user_device_bind", "id", UserDeviceBindModel.class);
		
		me.add(arp);

		int timeout = 30000;
		int port = 6379;
		try {
			timeout = Integer.parseInt(redisProp.get("redisTimeout"));
		} catch (NumberFormatException e) {
		}
		try {
			port = Integer.parseInt(redisProp.get("redisPort"));
		} catch (NumberFormatException e) {
		}
		// 添加redis
		RedisPlugin userRedisPlugin = new RedisPlugin("users", redisProp.get("redisUrl"), port, timeout,
				redisProp.get("redisPassword"));
		me.add(userRedisPlugin);
		//定时任务插件
		QuartzPlugin  quartzPlugin = new QuartzPlugin();
		me.add(quartzPlugin);
		// web环境不需要调用，非web环境需要调用
		// userRedisPlugin.start();
	}

	@Override
	public void configRoute(Routes me) {
		//登录拦截
		LoginInterceptor loginInterceptor = new LoginInterceptor();
		me.addInterceptor(loginInterceptor);
		
		//处理设备上送的消息
		
		me.add("/web/api/open/back", UserOpenController.class);
		me.add("/web/api/inner/user", UserInnerController.class);
		me.add("/web/api/inner/device", DeviceController.class);
		me.add("/web/api/open/wechat", WeChatOpenUserController.class);
		me.add("/web/api/inner/wechat", WeChatInnerUserController.class);
		me.add("/web/api/open/wechatMsg", WeChatMsgController.class);
		me.add("/web/api/inner/opr", WeChatDeviceOprController.class);
		
	}
	
	private ExecutorService executorService = Executors.newCachedThreadPool();

	@Override
	public void afterJFinalStart() {
		super.afterJFinalStart();
		Thread t = new Thread(new Runnable() {

			public void run() {
				try {
					IotMnsTaskListener iotMnsListener = new IotMnsTaskListener();
					iotMnsListener.setAccessKeyId(iotcfgProp.get("user.accessKeyID"));
					iotMnsListener.setAccessKeySecret(iotcfgProp.get("user.accessKeySecret"));
					iotMnsListener.setAccountEndpoint(iotcfgProp.get("carla.iot.queue.endpoint"));
					iotMnsListener.setQueueName(iotcfgProp.get("carla.iot.queue.name"));
					executorService.submit(iotMnsListener);
				} catch (Exception e) {
					logger.error("IotMnsTaskListener启动发生异常", e);
				} finally {

				}
			}
		});
		t.start();
	}
	
	@Override
	public void beforeJFinalStop() {
		super.beforeJFinalStop();
		try {
			if(executorService!=null && !executorService.isShutdown()){
				executorService.shutdown();
			}
		} catch (Exception e) {
			
		}
	}

}
